//
//  ST_PeculiarityGroupHeaderView.swift
//  btvideo
//
//  Created by mac on 2020/5/26.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyUserDefaults
import SwifterSwift
import SwiftyJSON
import SwiftyAttributes

class ST_PeculiarityGroupHeaderView: UIView {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.cornerRadius = 30
        self.backgroundColor = Color.white
        
        self.addSubview(video_progress_view)
        self.addSubview(like_sub_label)
        self.addSubview(pec_name_label)
        self.addSubview(content_label)
        self.addSubview(avatar_image_view)
        self.addSubview(center_oper_btn)
        self.addSubview(nickname_label)
        self.addSubview(sign_image_container)
        
        self.addSubview(user_info_label)
        
        pec_name_label.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            //            -20 或者 -88
//            make.bottom.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview().offset(-50)
            make.centerX.equalToSuperview()
        }
        
        like_sub_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
            make.height.equalTo(26)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.bottom.equalTo(pec_name_label.snp.top).offset(-15)
            make.height.equalTo(44)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.left.equalToSuperview().offset(15)
            make.bottom.equalTo(content_label.snp.top).offset(-15)
        }
        
        center_oper_btn.snp.makeConstraints { (make) in
            make.width.equalTo(68)
            make.height.equalTo(36)
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(avatar_image_view)
        }
        
        self.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.center.equalTo(avatar_image_view)
            make.width.height.equalTo(60)
        }
        
        
        nickname_label.snp.makeConstraints { (make) in
            
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.top.equalTo(avatar_image_view).offset(2)
            make.height.equalTo(22)
            
            if ScreenWidth < 400{
                make.width.lessThanOrEqualTo(135)
            }else{
                make.width.lessThanOrEqualTo(175)
            }
            
        }
        
        sign_image_container.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label.snp.right).offset(4)
            make.centerY.equalTo(nickname_label).offset(-1)
            make.width.equalTo(82)
            make.height.equalTo(22)
        }
        
        user_info_label.snp.makeConstraints { (make) in
            
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.top.equalTo(nickname_label.snp.bottom).offset(1)
            make.height.equalTo(17)
        }
        
        video_progress_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(avatar_image_view.snp.top).offset(-26)
            make.height.equalTo(ST_PlayVideoProgressView.height)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
        
    }
    
    deinit {
        print("特质组 释放内存")
    }
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self.parentViewController else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool , self.model?.group_id == id else{
            return
        }
        
        self.center_oper_btn.isSelected = isThumbUp
        
        self.model?.is_thumb_up = isThumbUp
        
        let offSet = isThumbUp ? 1 : -1
        
        self.model?.thumb_up_count += offSet
        
        self.set_up_thumbup_count_label()
        
            
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    weak var phDelegate:ST_PairsShareParticularViewDelegate?{
        didSet{
            self.pairsHeader?.phDelegate = self.phDelegate
        }
    }
    
    weak var pairsHeader:ST_PairsShareParticularView?
    
    //    MARK: - Share View
    /**
     和 create_play_view 方法二选一
     */
    func package_play_view(_ view:ST_PairsShareParticularView){
        
        pairsHeader = view
        
        self.insertSubview(view, belowSubview: video_progress_view)
        
        pairsHeader?.progress_closure = {[weak self] progress,idx in
            self?.video_progress_view.setProgress(percentValue: progress, currentIdx: idx)
        }
        
        //        view.roundCorners(cornerRadius: 30, allRoundCorner: false)
        pairsHeader?.isMuted = false
        pairsHeader?.phDelegate = self.phDelegate
        
    }
    //来自外部的 ST_PairsShareParticularView
    fileprivate var outsit_play_view = true
    /**
     和 package_play_view 方法二选一
     */
    func create_play_view(){
        
        let header = ST_PairsShareParticularView()
        
        self.insertSubview(header, belowSubview: video_progress_view)
        
        self.pairsHeader = header
        
        pairsHeader?.progress_closure = {[weak self] progress,idx in
            self?.video_progress_view.setProgress(percentValue: progress, currentIdx: idx)
        }
        
        pairsHeader?.phDelegate = self.phDelegate
        
        outsit_play_view = false
    }
    
    
    //    MARK: - Properties
    
    
    fileprivate lazy var like_sub_label:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.setImageForAllStates(ST_ImageUtils.imageName("特质_group_heart_icon")!)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.alpha = 0
        return control
    }()
    
    
    fileprivate lazy var pec_name_label:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 10
        control.setImageForAllStates(ST_ImageUtils.imageName("特质_group_icon")!)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0)
        control.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.backgroundColor = UIColor.init(hex: 0x42CEDA, transparency: 0.1)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#42CEDA")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
        control.alpha = 0
        control.addTarget(self, action: #selector(push_pec_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 22
        control.clipsToBounds = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(user_center_click_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        
        return control
    }()
    
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()
    
    fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    fileprivate lazy var sign_image_container:ST_UserSignView = {
        let control = ST_UserSignView()
        return control
    }()
    
    fileprivate lazy var user_info_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.numberOfLines = 0
        return control
    }()
    
    
    fileprivate lazy var video_progress_view:ST_PlayVideoProgressView = {
        let control = ST_PlayVideoProgressView()
        return control
    }()
    
    fileprivate lazy var center_oper_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 36/2.0
        control.alpha = 0
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xACB4C0)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.selected)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        
        control.setTitle("点赞", for: UIControl.State.normal)
        control.setTitle("已点赞", for: UIControl.State.selected)
        
        
        control.setTitleColor(UIColor.white, for: .normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(thumb_up_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    //    MARK: - Bind Model
    var model:ST_PeculiarityGroupHeaderViewModel?
    
    func bind_model(_ model:ST_PeculiarityGroupHeaderViewModel){
        
        self.model = model
        
        if pairsHeader == nil || model.nickname.count < 1{
            return
        }
        
        center_oper_btn.isSelected = model.is_thumb_up
        center_oper_btn.alpha = 1
        
        nickname_label.text = model.nickname
        
        
        
        sign_image_container.bind_data(isVip: CHECK_MEMBER_STATUS(expirationTime: model.vipExpire) == .subscribe, detectedFace: model.faceAuditState == 3)
        
        
        pec_name_label.setTitleForAllStates(model.peculiarityName + "     ")
        
        
        pec_name_label.alpha = 1
        
        
        
        avatar_image_view.pin_setImage(from: model.avatar.compress_small_image(width: 44*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        
        icon_supplement_image_view.pin_setImage(from: AVATAR_SUPPLEMENT(guardTime: model.guardTime, guardContent: model.guardContent)?.url)
        
        user_info_label.text = model.age.string + "岁" + " " + model.city
        
        
        if let atrr = model.signAttri,atrr.length > 0{
            content_label.attributedText = atrr
            content_label.snp.updateConstraints { (make) in
                make.height.equalTo(model.frameModel.content_height)
            }
            avatar_image_view.snp.updateConstraints({ (make) in
                make.bottom.equalTo(content_label.snp.top).offset(-15)
            })
        }else{
            
            content_label.attributedText = NSAttributedString()
            content_label.snp.updateConstraints { (make) in
                make.height.equalTo(model.frameModel.content_height)
            }
            
            avatar_image_view.snp.updateConstraints({ (make) in
                make.bottom.equalTo(content_label.snp.top).offset(5)
            })
        }
        
        if !outsit_play_view{
            
            pairsHeader?.setUp(data_array: model.albums)
            
        }else{
            
            pairsHeader?.supplement(newArray: model.albums)
            
        }
        
        set_up_progress_view(fromCount: model.albums.count)
        
        set_up_thumbup_count_label()
    }
    
    fileprivate func set_up_thumbup_count_label(){
        
        guard let  model = model else{ return }
        
        let str = model.thumb_up_count.st_number_description() + "位用户点赞  "
        
        like_sub_label.setTitleForAllStates(str)
        
        like_sub_label.alpha = 1
    }
    
    fileprivate func set_up_progress_view(fromCount:Int){
        
        video_progress_view.create_items(count: fromCount)
        
        video_progress_view.isHidden = fromCount < 2
        
        main_thread_execute(afterDelay: 0.5) {
            if fromCount > 0{
                self.video_progress_view.setProgress(percentValue: 1, currentIdx: 0)
            }
        }
        
    }
    
    
    
    func playerStatus(isMute:Bool){
        
        pairsHeader?.isMuted = isMute
    }
    
}

//MARK: - Event
extension ST_PeculiarityGroupHeaderView{
    
    @objc fileprivate func play_next_video(){
        
        self.pairsHeader?.scrollToNext()
    }
    
    @objc fileprivate func play_previous_video(){
        self.pairsHeader?.scrollToPrevious()
    }
    
    
    @objc fileprivate func thumb_up_click_handle(){
        
        guard let model = self.model else { return  }
        
        
        
        Thumbup(targetAccid: model.accid, groupId: model.group_id, peculiarity_id: model.peculiarity_id, thumbUpAction: !model.is_thumb_up, fromVC: self.parentViewController) { (err) in
            
            self.center_oper_btn.isSelected = !self.center_oper_btn.isSelected
            self.model?.is_thumb_up = !model.is_thumb_up
            
            let offSet = model.is_thumb_up ? 1 : -1
            
            self.model?.thumb_up_count += offSet
            
            self.center_oper_btn.isUserInteractionEnabled = err
            
            self.set_up_thumbup_count_label()
            
        } completion: {
        
            self.center_oper_btn.isUserInteractionEnabled = true
            
            print("点赞成功新Api Service")
            
        }
        
    }
    
    @objc fileprivate func follow_click_handle(){
        
        guard let m = self.model else { return  }
        
        if m.accid == ST_BTUserInfoManager.shared.current_account_info?.accid{
            
            let thumbUpHud = ST_BTHUDController.init(noticeText: "不能喜欢自己哦")
            
            GlobalPresent(toController: thumbUpHud, animated: false)
            
            main_thread_execute(afterDelay: 2.5) {
                thumbUpHud.dismiss(animated: false, completion: nil)
            }
            
            return
        }
        
        let info = ST_MatchUserInfo(accid: m.accid, avatar: m.avatar, nickname: m.nickname)
        
        FollowBehavior(info: info, followControl: self.center_oper_btn) { (f, err) in
            
            if let e = err{
                
                self.parentViewController?.toast(text: e)
                
            }
        }
        
        
    }
    
    
    @objc fileprivate func push_pec_handle(){
        
        
        guard let model = self.model else { return }
        
        var displayPerson = false
        
        if  model.peculiarityType == ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex?.rawValue{
            displayPerson = true
        }
        
        push_peculiarity(id: model.peculiarity_id.int ?? 0, onlyDisplayPerson: displayPerson, isToday: false, navigationController: self.parentViewController?.navigationController)
        
    }
    
    @objc fileprivate func send_msg_handle(){
        
        guard let m = self.model else { return }
        
        BINP.update_base_info(remoteInfo: ST_BTUserInfoFromRemote.init(accid: m.accid, avatar: m.avatar, userName: m.nickname))
        
        push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: m.accid, title: m.nickname, source: "个人特质页"), navigationController: nil)
        
        /*
         let vc = ST_PrivateChatViewController()
         
         vc.sessionID = m.accid
         
         vc.chatTitle = m.nickname
         
         vc.source = "个人特质页"
         
         GlobalPresent(toController: vc)
         */
    }
    
    @objc fileprivate func user_center_click_handle(){
        
        guard let accid = self.model?.accid else { return }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
        
    }
}

class ST_PeculiarityGroupHeaderFrameModel: NSObject {
    
    fileprivate let bottomSupplementHeight:CGFloat = 20 + 22 + 15 + 30
    
    var headerExtensionHeight = 80.cgFloat
    
    var content_height = 0.cgFloat
    
    var header_height = 100.cgFloat
    
    var remarkAttr = NSAttributedString()
    
    init(accid:String,remark:String,albumSize:CGSize,sex:ST_SEX = ST_SEX.unkown) {
        super.init()
        
        
        
        //        头像
        self.headerExtensionHeight = 20 + 44
        
        /* 取消
         //            同性隐藏关注和喜欢
         if sex == ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex{
         self.headerExtensionHeight += 20
         }
         
         else
         */
        
        /*  新需求取消了 中间那几个按钮
         
         //            不是自己
         if accid != Defaults[.currentUserID]{
         //            关注 和 喜欢 按钮
         self.headerExtensionHeight += 48 + 20
         }
         
         */
        /*
         else{
         self.headerExtensionHeight += 2
         }*/
        
        if remark.count < 1{
            self.content_height = 0
            //            【喜欢、特质标签】
            self.headerExtensionHeight += bottomSupplementHeight
        }else{
            
            let attrString = NSMutableAttributedString(string: remark)
            
            let p = NSMutableParagraphStyle()
            
            p.lineSpacing = 5
            
            p.alignment = .center
            
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hex: 0x333333)!,.paragraphStyle:p]
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            remarkAttr = attrString
            
            content_height = attrString.height(withConstrainedWidth: ScreenWidth - 30)
            
            self.headerExtensionHeight += content_height + bottomSupplementHeight + 15
            
        }
        
        let w = albumSize.width < 1 ? 1 : albumSize.width
        
        var h = ScreenWidth/w*albumSize.height
        
        if h > PairsShareHeaderMaxHeight{
            h = PairsShareHeaderMaxHeight
        }
        
        self.header_height = h + self.headerExtensionHeight
        
    }
    
}

class ST_PeculiarityGroupHeaderViewModel: NSObject {
    var remark = ""
    var nickname = ""
    var is_thumb_up = false
    var is_friends = false
    var age = 18
    var city = ""
    var avatar = ""
    var guardTime = 0
    var guardContent = ""
    var accid = ""
    var sex = ST_SEX.unkown
    var thumb_up_count = 0
    var is_attention = false
    
    var isSentProps = false
    
    var albums = [ST_PairsShareParticularModel]()
    var peculiarityName = ""
    
    var vipExpire = 0
    
    var faceAuditState = 0
    
    // 1男 2女
    var peculiarityType = 1
    
    //  other supplement properties
    var peculiarity_id = ""
    
    var group_id = ""
    
    var signAttri:NSAttributedString?
    
    var frameModel = ST_PeculiarityGroupHeaderFrameModel(accid: "", remark: "", albumSize: CGSize.zero)
    
    convenience init(user:JSON,list:[JSON]) {
        self.init()
        
        self.remark = user["remark"].stringValue
        self.nickname = user["nickname"].stringValue
        
        self.vipExpire = user["vip_expire"].intValue
        
        self.faceAuditState = user["face_audit_state"].intValue
        
        self.is_thumb_up = user["is_thumb_up"].boolValue
        
        self.is_friends = user["is_friend"].boolValue
        
        self.age = user["age"].intValue
        
        if let s = ST_SEX.init(rawValue: user["gender"].intValue){
            self.sex = s
        }
        
        self.city = user["city"].stringValue
        self.avatar = user["avatar"].stringValue
        self.guardTime = user["guard_time"].intValue
        self.guardContent = user["guard_content"].stringValue
        self.accid = user["accid"].stringValue
        self.thumb_up_count = user["thumb_up_count"].intValue
        self.is_attention = user["is_attention"].boolValue
        
        self.isSentProps = user["is_send_props"].boolValue
        
        self.albums = ST_PairsShareParticularModel.describe(json_array: list)
        
        //        /测试
        //        self.accid = "888"
        
        //        self.remark = ""
        //        测试 结束
        
        var size = CGSize.zero
        if let first = albums.first{
            size = CGSize.init(width: first.width, height: first.height)
        }
        
        self.frameModel = ST_PeculiarityGroupHeaderFrameModel.init(accid: self.accid, remark: self.remark, albumSize: size,sex: self.sex)
        
        signAttri = self.frameModel.remarkAttr
        
    }
    
}




